<?php
/////////////////////////////////////////////////////////////////////////////
//      Target Country by IP Address  - advanced redirection
//		- for MySql, Plain text databases-
//	Copyright (C) 2003 Jgsoft Associates - http://www.analysespider.com/
/////////////////////////////////////////////////////////////////////////////

include($anp_path."config.php");

//Get the real IP address of the user
$anp_ip = anp_realip();
$anp_ip_number = anp_ip2long($anp_ip);

$ip_blocked = 0;

if (strlen($anp_default_reject_link) > 0) 
  {
  // equals blocked IP
  if (anp_block_ips($anp_ip,$anp_ip_number)==1) 
     {
      $ip_blocked = 1;
      anp_redirect($anp_default_reject_link);
     }  
  }

if ($anp_db_type=="mysql") include($anp_path."anp_mysql_full.php"); 
if ($anp_db_type=="text") include($anp_path."anp_text_full.php");

if(_DEBUG_MODE=="2") ob_start();

if ("$anp_url_save_method"=="session") session_start();

$anp_cookie_name="anp_".substr(md5(_NODE_ID),0,10);

$anp_country_code=anp_get_cookie();

if ("$anp_country_code"=="none")
{
       if ($anp_ip_number>0)
       {
       $anp_country_code = anp_get_country($anp_ip,$anp_ip_number);

       //GB=Great Britain  UK=United Kingdom 
       if ($anp_country_code=="GB")
         $anp_country_code="UK";

	anp_save_cookie($anp_country_code);
       } 
}	

if ($ip_blocked == 0)
 {
  $anp_rr = anp_get_rules();
  $anp_url=anp_country_to_url($anp_country_code);
//  echo "mmm";
  anp_redirect($anp_url);
 }

if(_DEBUG_MODE=="2") ob_end_flush();

function anp_block_ips($ip,$ipn)
{	
     global $anp_path;

	$gh=fopen($anp_path."blocked_ips.dat","r");
	while(!feof($gh))
	{
		$line=trim(fgets($gh,41));
		if (strpos($line,";")>1) 
		{
			list($i1,$i2)=explode(";",$line);
			if (anp_ip_address_is_in_range($ipn,$i1,$i2)) 
			{
				if(_DEBUG_MODE) echo "The user is in the IP exception list<br>";
				fclose($gh);
				return (1);
			}
		}
		else 
		{
			if ("$ip"=="$line") 
			{
				if(_DEBUG_MODE) echo "The user is in the IP exception list<br>";
				fclose($gh);
				return (1);
			}
		}
	}
	fclose($gh);

	if(_DEBUG_MODE) echo "The user is NOT in the exception lists<br>";
	return (0);
}

function anp_get_rules()
{	     
   global $anp_path,$re_rules;

   $anp_rules = array();
   $a_list = array() ;
   $a_list = file($anp_path.$re_rules);

   $total = count($a_list);

   for($i = 0 ; $i < $total ; $i++) {
      $line=trim($a_list[$i]);

      if (strlen($line)>0 )
        {    
         $ipos = strpos($line,"#");
         if (!is_integer($ipos)) 
          {
           list($i1,$i2) = explode ("=", $line);
           $i1 = trim($i1); 
           $i2 = trim($i2); 
           $anp_rules["$i1"] = "$i2"; 
          }
         else
          {
            if ($ipos != 0)
             {
              $line = substr($line,0,$ipos);
              list($i1,$i2) = explode ("=", $line);
              $i1 = trim($i1); 
              $i2 = trim($i2); 
              $anp_rules["$i1"] = "$i2"; 
             }
          }
        } 
    }

  return $anp_rules;
}

// Returns the real IP address of the user
function anp_realip()
{
    // No IP found (will be overwritten by for
    // if any IP is found behind a firewall)
    $ip = FALSE;
    
    // User is behind a proxy and check that we discard RFC1918 IP addresses
    // if they are behind a proxy then only figure out which IP belongs to the
    // user.  Might not need any more hackin if there is a squid reverse proxy
    // infront of apache.
    if (!empty($_SERVER['HTTP_X_FORWARDED_FOR'])) {

        // Put the IP's into an array which we shall work with shortly.
        $ips = explode (", ", $_SERVER['HTTP_X_FORWARDED_FOR']);

        for ($i = 0; $i < count($ips); $i++) {
            // Skip RFC 1918 IP's 10.0.0.0/8, 172.16.0.0/12 and
            // 192.168.0.0/16 
            // below.
            if (!eregi ("^(10|172\.16|192\.168)\.", $ips[$i])) {
                $ip = $ips[$i];
                break;
            }
        }
    }
    // Return with the found IP or the remote address
    return ($ip ? $ip : $_SERVER['REMOTE_ADDR']);
}

function anp_ip2long ($IPaddr)
{
if ($IPaddr == "") {
	return 0;
} else {
	$ips = split ("\.", "$IPaddr");
       return ($ips[3] + $ips[2] * 256 + $ips[1] * 65536 + $ips[0] * 16777216);
	}
}

function anp_get_cookie()
{
	global $anp_url_save_method,$anp_cookie_name,$HTTP_COOKIE_VARS,$HTTP_SESSION_VARS;
	if ("$anp_url_save_method"=="cookie") $anp_country_code=$HTTP_COOKIE_VARS["$anp_cookie_name"."_CC"];
	if ("$anp_url_save_method"=="session") $anp_country_code=$HTTP_SESSION_VARS["$anp_cookie_name"."_CC"];
	if ("$anp_country_code"=="")  { $anp_country_code="none"; if(_DEBUG_MODE) echo "No country code is saved for current visitor (_DEBUG_MODE=1 prevents cookies to be sent) ; cookie name: $anp_cookie_name<br>";}
	if(_DEBUG_MODE) echo "Country Code for this visitor is loaded from COOKIE/SESSION: '$anp_country_code' <br>";
	return $anp_country_code;
}

function anp_save_cookie($c)
{
	global $anp_url_save_method,$anp_cookie_name;
	if ("$anp_url_save_method"=="cookie")
	{
		if(_DEBUG_MODE) echo "Visitor`s country code '$c' is saved in a COOKIE<br>";
		if(_DEBUG_MODE!="1") setcookie($anp_cookie_name."_CC","$c",time()+31536000);

	}
	if ("$anp_url_save_method"=="session")
	{
		if(_DEBUG_MODE) echo "Visitor`s country code '$c' is saved in a SESSION var<br>";
		$GLOBALS["$anp_cookie_name"."_CC"]="$c";
		session_unregister("$anp_cookie_name"."_CC");
		if(_DEBUG_MODE!="1") session_register("$anp_cookie_name"."_CC");
	}
}

function anp_redirect($url)
{
	if (strlen($url)!=0) 
	{
		if(_DEBUG_MODE) echo "The visitor should be redirected now to $url<br>";
		if(_DEBUG_MODE==0) header("Location: $url");
		die();
	}
	if(_DEBUG_MODE) echo "The visitor is not redirected. The page is loaded.<br>";
}

function anp_ip_address_is_in_range($ipn,$min0,$max0)
{
	$min=anp_ip2long ($min0);
	$max=anp_ip2long ($max0);
	return (anp_ip_number_is_in_range($ipn,$min,$max));
}

function anp_ip_number_is_in_range($ipn,$min,$max)
{
	if (($min <= $ipn) && ($ipn <= $max))	return(1);
	return (0);
}

function anp_country_to_url($c)
{
	global $anp_rr,$anp_default_redirect_link,$anp_default_reject_link;
	if(_DEBUG_MODE) echo "Finding the URL for country '$c' <br>";
	if ((!is_array($anp_rr)) || (strlen("$c")==0)) return($anp_default_reject_link);
	if (!isset($anp_rr[$c])) return($anp_default_reject_link);
	if (strlen($anp_rr[$c])==0) return ($anp_default_redirect_link);
	return ($anp_rr[$c]);
}

?>